package think.in.spring.bean;

import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.ResolvableType;
@Configuration
public class ObjectProviderDemo {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(ObjectProviderDemo.class);
        context.refresh();
        lookupByObjectProvider1(context);
        lookupByObjectProvider(context);
    }

    private static void lookupByObjectProvider1(AnnotationConfigApplicationContext context) {
        ResolvableType type = ResolvableType.forClass(Integer.class);
        ObjectProvider<Integer> beanProvider = context.getBeanProvider(type);
        //判断是否存在，如果不存在返回1111
        Integer ifAvailable = beanProvider.getIfAvailable(() -> 1111);
        System.out.println("ifAvailable:"+ifAvailable);
        //Bean不存在getIfUnique也返回true
        Integer ifUnique = beanProvider.getIfUnique(() -> 2222);
        System.out.println("ifUnique:"+ifUnique);
    }

    private static void lookupByObjectProvider(AnnotationConfigApplicationContext context) {
        ObjectProvider<String> beanProvider = context.getBeanProvider(String.class);
        //通过String能找到两个Bean对象如果使用ifAvailable会报错，只能使用unique
        String ifUnique = beanProvider.getIfUnique(() -> "test");
        System.out.println("ifUnique:"+ifUnique);
    }

    @Bean
    public String helloword1() {
        return "Hello word1";
    }
    @Bean
    public String helloword() {
        return "Hello word";
    }
}
